package com.gasstion.controller;

import com.gasstion.dao.*;
import com.gasstion.entity.*;
import com.gasstion.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Scope("prototype")
public class UserinfoController {
    @Autowired
    private UserInfoService userInfoService ;
    @Autowired
    private UserinfoDao userinfoDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;


    @RequestMapping("/query")
    @ResponseBody
    public List<Userinfo> query(){
        return userinfoDao.query();
    }

    @RequestMapping("/queryAll")
    @ResponseBody
    public List<Userinfo> queryAll(){
        return  userinfoDao.queryAll() ;
    }

    @RequestMapping("/querySearch")
    @ResponseBody
    public Map<String,Object> querySearch(String username, int offset, int limit){
        List<Userinfo> list = userInfoService.findAll(username,offset,limit) ;
        long count = userInfoService.findTotalCount(username);
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",list) ;
        map.put("total",count) ;
        return  map ;
    }

    // denglu
    @RequestMapping("/login")
    public String login(String workName, String upwd , HttpServletResponse res, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject() ;
        UsernamePasswordToken token = new UsernamePasswordToken(workName,upwd) ;
        
        try {
            subject.login(token);
            workName =  request.getParameter("workName");
            upwd = request.getParameter("upwd");
            Userinfo userinfo = userinfoDao.login(workName, upwd);
            if (userinfo!=null){
                if(userinfo.getState()==0){
                    request.getSession().setAttribute("error","你的用户已经被停用！");
                    return "redirect:/login.jsp";
                }else {
                    request.getSession().setAttribute("userinfo",userinfo);
                    //根据用户编号查询角色编号rid
                    int rid = userRoleDao.getRidByUid((int)userinfo.getUid());
                    //根据rid查询角色信息
                    Role role = roleDao.getRnameByRid(rid);
                    //根据rid查询。
                    //
                    // 8用户父权限
                    List<Permission> perList1 = permissionDao.getAllperByPid(rid);
                    List<Permission> perList2 = permissionDao.getChilid(rid);
                    List<Permission> perList = new ArrayList<>();
                    List<Permission> newList = new ArrayList<>();
                    //循环获得子权限
                    for (Permission permission : perList1){
                        if(permission.getParentid()==0){
                            perList.add(permission);
                            for (Permission permission1 : perList2){
                                if(permission.getPid()==permission1.getParentid()){
                                    newList.add(permission1);
                                    permission.setList(newList);
                                }
                            }

                        }

                        permission.setList(newList);
                    }
                    // 保存权限和角色
                    request.getSession().setAttribute("perList",perList);
                    request.getSession().setAttribute("role",role);
                    request.getSession().setAttribute("error","");
                    return "redirect:/index.jsp";
                }

            }
        }
        catch (UnknownAccountException e){
            e.printStackTrace();
            request.getSession().setAttribute("error","用户名不正确!");
            return "redirect:/login.jsp" ;
        }
        catch (AuthenticationException e) {
            e.printStackTrace();
            request.getSession().setAttribute("error","密码不正确!");
            return "redirect:/login.jsp" ;
        }
        request.getSession().setAttribute("error","用户名或密码错误！");
        return "redirect:/login.jsp";
    }

    // 退出
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        //
        request.getSession().removeAttribute("userinfo");
        Subject subject = SecurityUtils.getSubject() ;
        //取消认证
        subject.logout();
        return "redirect:/login.jsp" ;
    }


    @RequestMapping("/update")
    @ResponseBody
    public   Map<String,Object> update(Userinfo userinfo, int pn){
        userinfoDao.update(userinfo);
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",userInfoService.findAll("",(pn-1) * 2,2)) ;
        map.put("total",userInfoService.findTotalCount("")) ;
        return map;
    }


    @RequestMapping("/save")
    @ResponseBody
    public Map<String,Object> save(Userinfo userinfo,int pn){
        userinfoDao.save(userinfo);
        Map<String,Object> map = new HashMap<>() ;
        map.put("rows",userInfoService.findAll("",(pn-1) * 2,2)) ;
        map.put("total",userInfoService.findTotalCount("")) ;
        return map;
    }

    @RequestMapping("/del")
    @ResponseBody
    public   Map<String,Object> del(String ids,int pn){
        String[] ss = ids.split("-");
        Integer[] myids = new Integer[ss.length] ;
        for(int i=0;i<ss.length;i++){
            System.out.println(ss[i]);
            myids[i] = Integer.parseInt(ss[i]) ;
        }
        userinfoDao.del(myids);
        Map<String,Object> map = new HashMap<>() ;
        int limit = 0 ;
        long tcount = userinfoDao.getTotalCount("") ;
        long pg = 0 ;
        if(tcount % 2 ==0){
            pg = tcount / 2 ;
        }
        else{
            pg = tcount / 2 +1 ;
        }

        if(pg==pn){
            limit = (pn-1) * 2 ;
        }
        else{
            limit =  (pn-2) * 2 ;
        }
        map.put("rows",userInfoService.findAll("",limit,2)) ;
        map.put("total",userInfoService.findTotalCount("")) ;
        return map;
    }

    @RequestMapping("/fenPei")
    @ResponseBody
    public  Map<String,Object> doFenPei(int uid,int rid){
        Map<String,Object> map = new HashMap<>() ;

        UserRole userRole =  userRoleDao.getRoleByUserId(uid) ;
        if(userRole!=null) {
            userRoleDao.update(uid, rid);
        }
        else{
            userRoleDao.save(uid,rid) ;
        }
        map.put("rows",userInfoService.findAll("",0,2)) ;
        map.put("total",userInfoService.findTotalCount("")) ;
        return map;
    }

}
